package com.lindroy.androidplayer.logic.network

import com.elvishew.xlog.XLog
import com.google.gson.Gson
import com.google.gson.JsonParseException
import com.lindroy.androidplayer.logic.model.ErrorBodyModel
import com.lindroy.androidplayer.logic.network.base.http.NotLoginException
import com.lindroy.androidplayer.logic.network.base.http.RequestException
import com.lindroy.androidplayer.logic.network.enums.HttpError
import retrofit2.HttpException
import java.net.UnknownHostException

/**
 * @author Lin
 * @date 2021/10/20
 * @function 处理返回的异常
 */

fun handleException(throwable: Throwable) = when (throwable) {
    is UnknownHostException -> RequestException(HttpError.NETWORK_ERROR, throwable.message)
    is HttpException -> {
        val errorModel = throwable.response()?.errorBody()?.string()?.run {
            Gson().fromJson(this, ErrorBodyModel::class.java)
        } ?: ErrorBodyModel()
        RequestException(errorMsg = errorModel.message, error = errorModel.error)
    }
    is JsonParseException -> RequestException(HttpError.JSON_PARSE_ERROR, throwable.message)
    is RequestException -> handleCusException(throwable)
    else -> RequestException(HttpError.UNKNOWN, throwable.message)
}

private fun handleCusException(exception: RequestException) = when (exception.code) {
    HttpError.NOT_LOGIN.code -> NotLoginException(exception.code, exception.errorMsg.orEmpty())
    else -> exception
}

